<template>
  <div class="edit-page-wrap">
    <Head title="基础信息">
      <template #content>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="140px"
          class="edit-form-wrap"
        >
          <el-form-item label="企业名称" prop="orgName">
            <el-input
              v-model.trim="ruleForm.orgName"
              placeholder="请输入企业名称"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item label="企业身份" prop="type" v-if="orgType == '0'">
            <el-radio-group
              v-model="ruleForm.type"
              :disabled="Boolean(id)"
              v-for="(item, index) in optionsS.corporateIdentity1"
              :key="index"
              @change="hanleType"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="企业身份" prop="type" v-if="orgType == '1'">
            <el-radio-group
              v-model="ruleForm.type"
              :disabled="Boolean(id)"
              v-for="(item, index) in optionsS.corporateIdentity2"
              :key="index"
              @change="hanleType"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="企业身份"
            prop="type"
            v-if="orgType == 'CHANNEL'"
          >
            <el-radio-group
              v-model="ruleForm.type"
              :disabled="Boolean(id)"
              v-for="(item, index) in optionsS.corporateIdentity"
              :key="index"
              @change="hanleType"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="运营商属性"
            prop="attr"
            v-if="ruleForm.type == '0'"
          >
            <el-radio-group
              v-model="ruleForm.attr"
              v-for="(item, index) in optionsS.operatorProperties"
              :disabled="Boolean(id)"
              :key="index"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="运营商名称"
            prop="operatorName"
            v-if="ruleForm.type == '0'"
          >
            <el-input
              v-model.trim="ruleForm.operatorName"
              placeholder="请输入运营商名称"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="账号"
            prop="accountNumber"
            v-if="ruleForm.type == '4' || ruleForm.type == '2'"
          >
            <el-input
              :disabled="Boolean(id)"
              v-model.trim="ruleForm.accountNumber"
              placeholder="请输入账号"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="用户名"
            prop="userName"
            v-if="ruleForm.type == '4' || ruleForm.type == '2'"
          >
            <el-input
              :disabled="Boolean(id)"
              v-model.trim="ruleForm.userName"
              placeholder="请输入用户名"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="手机号码"
            prop="mobile"
            v-if="ruleForm.type == '4' || ruleForm.type == '2'"
          >
            <el-input
              :disabled="Boolean(id)"
              v-model.trim="ruleForm.mobile"
              placeholder="请输入手机号码"
              maxlength="11"
              clearable
            />
          </el-form-item>
          <el-form-item label="企业注册地址" prop="address">
            <el-input
              v-model.trim="ruleForm.address"
              placeholder="请输入企业注册地址"
              maxlength="50"
              clearable
            />
          </el-form-item>
          <el-form-item label="统一社会信用代码" prop="code">
            <el-input
              v-model.trim="ruleForm.code"
              placeholder="请输入统一社会信用代码"
              maxlength="18"
              clearable
            />
          </el-form-item>
          <el-form-item label="归属城市" prop="cityCodes">
            <el-cascader
              ref="cityRef"
              popper-class="qc-cascader"
              v-model="ruleForm.cityCodes"
              :options="optionsS.city"
              @change="handleChangeCity"
              placeholder="请选择归属城市"
              clearable
            />
          </el-form-item>
          <el-form-item label="签约时间" prop="signTime">
            <div class="edit-date-wrap">
              <el-date-picker
                v-model="ruleForm.signTime"
                popper-class="qc-date"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </div>
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <div class="edit-line"></div>
    <Head title="结算设置" v-if="ruleForm.type == '0'">
      <template #content>
        <el-form
          ref="ruleFormRef1"
          :model="ruleForm"
          :rules="rules"
          label-width="140px"
          class="edit-form-wrap"
        >
          <el-form-item
            label="平台自动结算"
            prop="autoSettle"
            class="has-tips"
            v-if="env_type"
          >
            <el-radio-group
              v-model="ruleForm.autoSettle"
              v-for="(item, index) in YES_NO"
              :key="index"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
            <div class="tip">
              <div class="icon"></div>
              充电结束设备未上送、运营商未推送结算数据情况，是否按平台计算结果（依据实时数据）进行扣费结算
            </div>
          </el-form-item>
          <el-form-item
            label="是否支持开票"
            prop="supportInvoice"
            class="has-tips"
          >
            <el-radio-group
              v-model="ruleForm.supportInvoice"
              v-for="(item, index) in YES_NO"
              :key="index"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
            <div class="tip">
              <div class="icon"></div>
              设置该运营商的充电场站是否支持开票
            </div>
          </el-form-item>
          <el-form-item
            label="对账时间依据"
            prop="settlementTime"
            class="has-tips"
            v-if="ruleForm.attr == '3'"
          >
            <el-radio-group
              v-model="ruleForm.settlementTime"
              v-for="(item, index) in optionsS.settlementTimeData"
              :key="index"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
            <div class="tip">
              <div class="icon"></div>
              设置互联互通对账时间依据，即选择“启动充电时间"或"支付时间"在对账期内的订单进行对账，不建议随意修改
            </div>
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <div class="edit-line" v-if="ruleForm.type == '0'"></div>
    <Head
      title="充电限制"
      v-if="
        ruleForm.type == '1' || ruleForm.type == '2' || ruleForm.type == '4'
      "
    >
      <template #content>
        <el-form
          ref="ruleFormRef2"
          :model="ruleForm"
          :rules="rules"
          label-width="140px"
          class="edit-form-wrap"
        >
          <el-form-item
            label="充电阈值"
            prop="chargingThreshold"
            class="has-tips"
          >
            <el-input
              v-model.trim="ruleForm.chargingThreshold"
              placeholder="请输入充电阈值"
              maxlength="10"
              clearable
            />
            元
          </el-form-item>
          <el-form-item
            label="是否限制充电站"
            prop="isLimit"
            v-if="ruleForm.type == '1'"
          >
            <el-radio-group
              v-model="ruleForm.isLimit"
              v-for="(item, index) in optionsS.stationLimitTypeData"
              :key="index"
              @change="isLimitChange"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <div v-if="ruleForm.isLimit == '1' && ruleForm.type == '1'">
            <el-form-item label="可用电站" prop="limitType">
              <el-radio-group
                v-model="ruleForm.limitType"
                v-for="(item, index) in limteStationData"
                :key="index"
                @change="limitTypeChange"
              >
                <el-radio :label="item.value">{{ item.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label=""
              prop="orgIds"
              v-if="ruleForm.limitType == '0'"
            >
              <QcTree
                ref="orgTree"
                :data="optionsS.treeData"
                :showCheckbox="true"
                :checkStrictly="true"
                :setCheckedKeys="optionsS.setCompanyChecked"
                @handleCheck="handleOrgCheck"
              ></QcTree>
            </el-form-item>
            <el-form-item
              label=""
              prop="stationIds"
              v-if="ruleForm.limitType == '1'"
            >
              <QcTree
                ref="stationTree"
                :data="optionsS.stationTreeData"
                :showCheckbox="true"
                @handleCheck="handleStationCheck"
              ></QcTree>
            </el-form-item>
          </div>
        </el-form>
      </template>
    </Head>
    <div
      class="edit-line"
      v-if="
        ruleForm.type == '1' || ruleForm.type == '2' || ruleForm.type == '4'
      "
    ></div>
    <Head
      title="占用收费规则设置"
      v-if="
        ruleForm.type == '1' || ruleForm.type == '2' || ruleForm.type == '4'
      "
    >
      <template #content>
        <el-form
          ref="ruleFormRef3"
          :model="ruleForm"
          :rules="rules"
          label-width="140px"
          class="edit-form-wrap"
        >
          <el-form-item
            label="是否实际扣费"
            prop="isDeduction"
            class="has-tips"
          >
            <el-radio-group
              v-model="ruleForm.isDeduction"
              v-for="(item, index) in YES_NO"
              :key="index"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
            <div class="tip">
              <div class="icon"></div>
              温馨提示：设置不扣费后，平台正常生成占位订单，但不实际扣取用户费用
            </div>
          </el-form-item>
          <el-form-item
            label="单笔扣费上限"
            class="has-tips"
            prop="superiorLimit"
            v-if="ruleForm.isDeduction == '0'"
          >
            <el-input
              v-model.trim="ruleForm.superiorLimit"
              placeholder="设置占用订单最大扣费金额"
              maxlength="10"
              clearable
            />
            元
            <div class="tip">
              <div class="icon"></div>
              示例：设置扣费上限为10元，单笔占用订单计费为20元时，仅收取用户10元费用
            </div>
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <div
      class="edit-line"
      v-if="
        ruleForm.type == '1' || ruleForm.type == '2' || ruleForm.type == '4'
      "
    ></div>
    <Head title="结算设置" v-if="ruleForm.type == '2' || ruleForm.type == '4'">
      <template #content>
        <el-form
          ref="ruleFormRef1"
          :model="ruleForm"
          :rules="rules"
          label-width="140px"
          class="edit-form-wrap"
        >
          <el-form-item
            label="对账时间依据"
            prop="settlementTime"
            class="has-tips"
          >
            <el-radio-group
              v-model="ruleForm.settlementTime"
              v-for="(item, index) in optionsS.settlementTimeData"
              :key="index"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
            <div class="tip">
              <div class="icon"></div>
              设置互联互通对账时间依据，即选择“启动充电时间"或"支付时间"在对账期内的订单进行对账，不建议随意修改
            </div>
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <div
      class="edit-line"
      v-if="ruleForm.type == '2' || ruleForm.type == '4'"
    ></div>
    <Head title="其他信息">
      <template #content>
        <el-form
          ref="ruleFormOtherRef"
          :model="ruleForm"
          :rules="rules"
          label-width="140px"
          class="edit-form-wrap"
        >
          <el-form-item
            label="客服热线"
            prop="hotLine"
            v-if="ruleForm.type == '0'"
            class="has-tips"
          >
            <el-input
              v-model.trim="ruleForm.hotLine"
              placeholder="请输入客服热线"
              maxlength="30"
              clearable
            />
            <div class="tip">
              <div class="icon"></div>
              运营商的客服电话，在移动端电站详情页展示供充电用户拨打（充电异常、咨询等）
            </div>
          </el-form-item>
          <el-form-item label="联系人" prop="contactUser">
            <el-input
              v-model.trim="ruleForm.contactUser"
              placeholder="请输入联系人"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item label="联系方式" prop="contactNum">
            <el-input
              v-model.trim="ruleForm.contactNum"
              placeholder="请输入联系方式"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item label="联系地址" prop="contactAddress">
            <el-input
              v-model.trim="ruleForm.contactAddress"
              placeholder="请输入联系地址"
              maxlength="50"
              clearable
            />
          </el-form-item>
          <el-form-item label="联系邮箱" prop="email">
            <el-input
              v-model.trim="ruleForm.email"
              placeholder="请输入联系邮箱"
              maxlength="50"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="营业执照"
            prop="businessLicense1"
            v-if="ruleForm.type == '0'"
            class="has-tips"
          >
            <QcUpload
              :valueModel="ruleForm.businessLicense1"
              :bodyData="{ path: 'org' }"
              @on-success="handleSuccessLogo"
              @before-upload="beforeUploadLogo"
              @on-error="handleErrorLogo"
              tip="温馨提示：为响应“《电子商务法》第十五条”规定，请上传清晰的营业执照用于移动端场站信息展示，图片支持格式jpg/jpeg/png，且不超过2M"
            ></QcUpload>

            <div class="tip">
              <div class="icon"></div>
              <el-tooltip effect="dark" placement="bottom-start">
                <template #content>
                  《电子商务法》第十五条明确规定：电子商务经营者（注：指商家）应当在其首页显著位置，持续公示营业执照信息、与其经营业务有关的行政许可信息。<br />因此，本条规定电子商务经营者应该在其店铺首页显著位置公示营业执照和许可信息，或提供链接标识，对于不需要办理营业执照需要标注清楚。<br />商家的店铺，需要展示营业执照和许可信息，接受公众的监督，电商交易平台需要核实真实性。如营业执照或许可证信息变更后，需要及时更新公示。</template
                >
                《电子商务法》第十五条
              </el-tooltip>
            </div>
          </el-form-item>
          <el-form-item label="营业执照" prop="businessLicense" v-else>
            <QcUpload
              :valueModel="ruleForm.businessLicense"
              @on-success="handleSuccessLogo"
              @before-upload="beforeUploadLogo"
              @on-error="handleErrorLogo"
              tip="温馨提示：只能上传jpg/jpeg/png文件，且不超过2M"
            ></QcUpload>
          </el-form-item>
          <el-form-item label="备注说明" prop="remark">
            <el-input
              v-model.trim="ruleForm.remark"
              placeholder="请输入备注说明"
              maxlength="200"
              type="textarea"
              :rows="3"
              show-word-limit
              clearable
            />
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <div class="edit-line"></div>
    <div class="edit-btn-wrap">
      <el-button type="primary" plain @click="back">取消</el-button>
      <el-button type="primary" v-btnAntiShake="onSubmit">保存</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import type { FormInstance, FormRules, UploadProps } from 'element-plus';
import Head from '@/components/head/index.vue';
import QcUpload from '@/components/qcUpload/index.vue';
import QcTree from '@/components/qcTree/index.vue';
import { getCity, getDay } from '@/utils/utils';
import {
  addCompany,
  updateCompany,
  queryCompanyDetail,
} from '@/service/apis/enterprise';
import { queryCarList, stationTreeDataByChannel } from '@/service/apis/org';
import {
  IS_PHONE_NUM,
  IS_EN_NUMBER_18,
  IS_NUM_AND_EN,
  IS_INTEGER,
  IS_DECIMAL_2,
  IS_TWO_DECIMAL,
} from '@/utils/verify';
import {
  CORPORATE_IDENTITY_TYPE,
  ATTR_TYPE,
  YES_NO,
} from '@/utils/dictionaries';
import { queryDicByParent } from '@/service/apis/api';

const router = useRouter();
const route = useRoute();
const {
  query: { id, cityCode },
} = route;
const ruleFormRef = ref<FormInstance>();
const ruleFormRef1 = ref<FormInstance>();
const ruleFormRef2 = ref<FormInstance>();
const ruleFormRef3 = ref<FormInstance>();
const ruleFormOtherRef = ref<FormInstance>();

const env_type = import.meta.env.VITE_ENV_TYPE !== 'ryc';

// 获取运营商id
const handleOrgCheck = (data: any, checkedData: any, checkedChildData: any) => {
  // ruleForm.orgIds = checkedData.checkedKeys
  ruleForm.orgIds = checkedChildData;
  // const aa = ruleForm?.orgIds.join(',')
  // ruleForm.chargerDto.orgIds = checkedData.checkedKeys
  ruleForm.chargerDto.orgIds = checkedChildData;
  ruleFormRef2.value?.validateField('orgIds');
};

// 获取站点id
const handleStationCheck = (
  data: any,
  checkedData: any,
  checkedChildData: any
) => {
  // ruleForm.stationIds = checkedData.checkedKeys
  ruleForm.stationIds = checkedChildData;
  // const aa = ruleForm?.orgIds.join(',')
  // ruleForm.chargerDto.stationIds = checkedData.checkedKeys
  ruleForm.chargerDto.stationIds = checkedChildData;
  ruleFormRef2.value?.validateField('stationIds');
};

const hanleType = (e: any) => {
  console.log(e);
  if (e == '0') {
    ruleForm.businessLicense1 = '';
  } else {
    ruleForm.businessLicense = '';
  }
};

let limteStationData = reactive([] as any);
limteStationData = [
  {
    value: '0',
    label: '选择运营商',
  },
  {
    value: '1',
    label: '选择电站',
  },
];

const errLogo = ref('');
const checkLogo = (rule: any, value: any, callback: any) => {
  console.log(errLogo.value);
  console.log(value);
  if (!value) {
    if (errLogo.value === 'type') {
      callback(new Error('上传的图片格式不正确'));
    } else if (errLogo.value === 'size') {
      callback(new Error('上传的图片大于2M'));
    } else if (errLogo.value === 'error') {
      callback(new Error('上传失败'));
    }
  }
  callback();
};

// 营业执照
const handleSuccessLogo = (val: any) => {
  if (ruleForm.type == '0') {
    ruleForm.businessLicense1 = val;
    ruleFormOtherRef?.value?.validateField('businessLicense1');
  } else {
    ruleForm.businessLicense = val;
    ruleFormOtherRef?.value?.validateField('businessLicense');
  }
};
const handleErrorLogo = () => {
  errLogo.value = 'error';
  if (ruleForm.type == '0') {
    ruleFormOtherRef?.value?.validateField('businessLicense1');
  } else {
    ruleFormOtherRef?.value?.validateField('businessLicense');
  }
};

const beforeUploadLogo = (type: string) => {
  errLogo.value = type;
  if (type) {
    if (ruleForm.type == '0') {
      ruleFormOtherRef?.value?.validateField('businessLicense1');
    } else {
      ruleFormOtherRef?.value?.validateField('businessLicense');
    }
  }
};

let optionsS = reactive({
  // org: [] as any,
  city: [] as any,
  treeData: [] as any,
  stationTreeData: [] as any,
  setCompanyChecked: [] as any,
  corporateIdentity: [] as any,
  corporateIdentity1: [] as any,
  corporateIdentity2: [] as any,
  operatorProperties: [] as any,
  settlementTimeData: [] as any,
  stationLimitTypeData: [] as any,
});

// 获取省市
getCity().then((res: any) => {
  optionsS.city = res;
});

let ruleForm = reactive({
  id: undefined as unknown,
  orgName: '',
  type: '0',
  attr: '0',
  operatorName: '',
  mobile: '',
  userName: '',
  accountNumber: '',
  userDTO: {
    mobile: '',
    userName: '',
    accountNumber: '',
  },
  hotLine: '',
  address: '',
  code: '',
  cityCodes: [] as any,
  cityName: '',
  cityCode: '',
  provinceCode: '',
  contactUser: '',
  contactNum: '',
  contactAddress: '',
  email: '',
  businessLicense: '',
  businessLicense1: '',
  remark: '',
  isDeduction: '1', // 是否扣费0是1否
  superiorLimit: '',
  supportInvoice: '0',
  signTime: [] as any,
  signStartTime: '',
  signEndTime: '',
  chargingThreshold: '',
  stationIds: [] as any,
  autoSettle: '1',
  isLimit: '1',
  limitType: '0',
  orgIds: [],
  chargerDto: {
    chargingThreshold: '',
    stationIds: [] as any,
    isLimit: '',
    limitType: '',
    orgIds: [] as any,
  },
  settlementTime: '1',
});

const checkTreeOrg = (rule: any, value: any, callback: any) => {
  const arr: any = [];
  const treeOrg = orgTree.value?.getCheckedNodes();
  treeOrg.forEach((item: any) => {
    if (item.type !== 'CHANNEL') {
      arr.push(item.id);
    }
  });
  if (arr.length === 0) {
    callback(new Error('请选择具体的电站运营商'));
  }
  callback();
};
const rules = reactive<FormRules>({
  orgName: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择企业身份', trigger: 'change' }],
  attr: [{ required: true, message: '请选择运营商属性', trigger: 'change' }],
  operatorName: [
    { required: true, message: '请输入运营商名称', trigger: 'blur' },
  ],
  accountNumber: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    {
      pattern: IS_NUM_AND_EN,
      message: '请输入正确的账号(由字母或数字组成,但必须含有字母)',
      trigger: 'blur',
    },
  ],
  userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {
      pattern: IS_PHONE_NUM,
      message: '请输入正确的手机号',
      trigger: 'blur',
    },
  ],
  address: [{ required: true, message: '请输入企业注册地址', trigger: 'blur' }],
  code: [
    { required: true, message: '请输入统一社会信用代码', trigger: 'blur' },
    {
      pattern: IS_EN_NUMBER_18,
      message: '请输入正确的统一社会信用代码',
      trigger: 'blur',
    },
  ],
  cityCodes: [
    { required: false, message: '请选择归属城市', trigger: ['blur', 'change'] },
  ],
  isLimit: [
    {
      required: true,
      message: '请选择是否限制充电站',
      trigger: ['blur', 'change'],
    },
  ],
  isDeduction: [
    { required: true, message: '请选择是否实际扣费', trigger: 'change' },
  ],
  superiorLimit: [
    { required: true, message: '请输入单笔扣费上限', trigger: 'blur' },
    {
      pattern: IS_DECIMAL_2,
      message: '请输入正确的单笔扣费上限，精确到2位小数',
      trigger: 'blur',
    },
  ],
  autoSettle: [
    { required: true, message: '请选择平台自动结算', trigger: 'change' },
  ],
  supportInvoice: [
    { required: true, message: '请选择是否支持开票', trigger: 'change' },
  ],
  hotLine: [
    { required: true, message: '请输入客服热线', trigger: 'blur' },
    {
      pattern: IS_INTEGER,
      message: '请输入正确的客服热线',
      trigger: 'blur',
    },
  ],
  contactUser: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  contactNum: [{ required: true, message: '请输入联系方式', trigger: 'blur' }],
  contactAddress: [
    { required: true, message: '请输入联系地址', trigger: 'blur' },
  ],
  email: [{ required: true, message: '请输入联系邮箱', trigger: 'blur' }],
  businessLicense: [
    { required: false, message: '请上传营业执照', trigger: 'change' },
    { validator: checkLogo, trigger: 'change' },
  ],
  businessLicense1: [
    { validator: checkLogo, trigger: 'change' },
    { required: true, message: '请上传营业执照', trigger: 'change' },
  ],
  remark: [{ required: false, message: '请输入备注', trigger: 'blur' }],
  chargingThreshold: [
    { required: true, message: '请输入充电阈值', trigger: 'blur' },
    {
      pattern: IS_TWO_DECIMAL,
      message: '请输入正确的充电阈值,，保留2位小数',
      trigger: 'blur',
    },
  ],
  orgIds: [
    {
      required: true,
      message: '请选择对应运营商',
      trigger: ['blur', 'change'],
    },
    { validator: checkTreeOrg, trigger: ['blur', 'change'] },
  ],
  stationIds: [
    { required: true, message: '请选择对应电站', trigger: ['blur', 'change'] },
  ],
  settlementTime: [
    {
      required: true,
      message: '请选择对账时间依据',
      trigger: ['blur', 'change'],
    },
  ],
});

queryDicByParent({
  listDtos: [
    'corporateIdentity',
    'operatorProperties',
    'stationLimitType',
    'settlementTime',
  ],
}).then((res: any) => {
  optionsS.corporateIdentity = res.corporateIdentity;
  optionsS.corporateIdentity1 = res.corporateIdentity.filter(
    (item: any) => item.value === '0'
  );
  optionsS.corporateIdentity2 = res.corporateIdentity.filter(
    (item: any) => item.value === '1'
  );
  optionsS.operatorProperties = res.operatorProperties;
  optionsS.settlementTimeData = res.settlementTime;
  optionsS.stationLimitTypeData = res.stationLimitType;
});

// 城市数据整合
const cityRef = ref();
const handleChangeCity = (e: any) => {
  if (e) {
    ruleForm.cityCodes = e;
    ruleForm.cityCode = e[1];
    ruleForm.provinceCode = e[0];
    const node = cityRef.value.getCheckedNodes()[0];
    ruleForm.cityName = node.pathLabels[1];
    console.log('e===node', e, node);
  } else {
    ruleForm.cityCodes = [];
    ruleForm.cityCode = '';
    ruleForm.provinceCode = '';
    ruleForm.cityName = '';
  }
};

queryCarList({}).then((res: any) => {
  if (res) {
    console.log([...res]);
    optionsS.treeData = [...res];
  }
});

stationTreeDataByChannel({ cecType: 2 }).then((res: any) => {
  if (res) {
    console.log([...res]);
    optionsS.stationTreeData = [...res];
  }
});

// 返回
const back = () => {
  router.go(-1);
};

const orgType = window.localStorage.getItem('orgType');
console.log(orgType, 'orgType=====');

// 编辑回填数据
let orgTree = ref();
let stationTree = ref();
if (id) {
  console.log(id);
  queryCompanyDetail({
    id: id,
  }).then((res: any) => {
    if (res) {
      ruleForm.id = res.id;
      ruleForm.orgName = res.orgName;
      ruleForm.type = res.type;
      ruleForm.attr = res.attr;
      ruleForm.operatorName = res.operatorName;
      ruleForm.mobile = res?.user?.mobile;
      ruleForm.userName = res?.user?.userName;
      ruleForm.accountNumber = res?.user?.accountNumber;
      ruleForm.userDTO.mobile = res?.user?.mobile;
      ruleForm.userDTO.userName = res?.user?.userName;
      ruleForm.userDTO.accountNumber = res?.user?.accountNumber;
      ruleForm.address = res.address;
      ruleForm.code = res.code;
      ruleForm.cityCodes = [res.provinceCode, res.cityCode];
      ruleForm.cityName = res.cityName;
      ruleForm.cityCode = res.cityCode;
      ruleForm.provinceCode = res.provinceCode;
      ruleForm.hotLine = res.hotLine;
      ruleForm.contactUser = res.contactUser;
      ruleForm.contactNum = res.contactNum;
      ruleForm.contactAddress = res.contactAddress;
      ruleForm.email = res.email;
      // ruleForm.businessLicense = res.businessLicense;
      if (res.type == 0) {
        ruleForm.businessLicense1 = res.businessLicense;
      } else {
        ruleForm.businessLicense = res.businessLicense;
      }
      ruleForm.remark = res.remark;
      ruleForm.isDeduction = res.isDeduction; // 是否扣费0是1否
      ruleForm.superiorLimit = res.superiorLimit;
      ruleForm.supportInvoice = res.supportInvoice;
      ruleForm.signTime = [res.signStartTime, res.signEndTime];
      ruleForm.signStartTime = res.signStartTime;
      ruleForm.signEndTime = res.signEndTime;
      ruleForm.chargingThreshold = res.charge?.chargingThreshold;
      ruleForm.stationIds = res.charge?.stationIds;
      ruleForm.isLimit = res.charge?.isLimit;
      ruleForm.limitType = res.charge?.limitType;
      ruleForm.orgIds = res.charge?.orgIds;
      ruleForm.chargerDto.chargingThreshold = res.charge?.chargingThreshold;
      ruleForm.chargerDto.stationIds = res.charge?.stationIds;
      ruleForm.chargerDto.isLimit = res.charge?.isLimit;
      ruleForm.chargerDto.limitType = res.charge?.limitType;
      ruleForm.chargerDto.orgIds = res.charge?.orgIds;
      ruleForm.chargerDto.stationIds = res.charge?.stationIds;
      ruleForm.settlementTime = res.settlementTime;
      ruleForm.autoSettle = res.autoSettle;

      console.log('ruleForm---', ruleForm);
      if (ruleForm.limitType == '0') {
        setTimeout(() => {
          // const targetIds = res?.targetIds.split(",")
          orgTree.value!.setCheckedKeys(res.charge.orgIds);
        }, 500);
      }
      if (ruleForm.limitType == '1') {
        setTimeout(() => {
          // const targetIds = res?.targetIds.split(",")
          stationTree.value!.setCheckedKeys(res.charge.stationIds);
        }, 500);
      }
    }
  });
} else {
  if (orgType === '1') {
    ruleForm.type = '1';
  } else if (orgType === '2' || orgType === '3' || orgType === '4') {
    ruleForm.type = '';
  } else {
    ruleForm.type = '0';
  }
}

const limitTypeChange = (e: any) => {
  console.log(e);
};

const isLimitChange = (e: any) => {
  console.log(e);
};

// 新增/修改提交
const emit = defineEmits(['clear-cache']);
const onSubmit = async () => {
  console.log('submit---', ruleForm);
  let other = true;
  if (!ruleFormRef.value || !ruleFormOtherRef.value) return;
  errLogo.value = '';
  try {
    await Promise.all([
      ruleFormRef.value.validate(),
      ruleFormOtherRef.value.validate(),
    ]);
  } catch (fields: any) {
    for (const key in ruleForm) {
      if (fields[key]) {
        ruleFormRef.value.scrollToField(key);
        ruleFormOtherRef.value.scrollToField(key);
        break;
      }
    }
    other = false;
    // return;
  }
  if (ruleForm.type == '0') {
    if (!ruleFormRef1.value) return;
    try {
      await Promise.all([ruleFormRef1.value.validate()]);
    } catch (fields: any) {
      for (const key in ruleForm) {
        if (fields[key]) {
          ruleFormRef1.value.scrollToField(key);
          break;
        }
      }
      return;
    }
    if (!other) return;
  }
  if (ruleForm.type == '1' || ruleForm.type == '2' || ruleForm.type == '4') {
    if (!ruleFormRef2.value || !ruleFormRef3.value) return;
    try {
      await Promise.all([
        ruleFormRef2.value.validate(),
        ruleFormRef3.value.validate(),
      ]);
    } catch (fields: any) {
      for (const key in ruleForm) {
        if (fields[key]) {
          ruleFormRef2.value.scrollToField(key);
          ruleFormRef3.value.scrollToField(key);
          break;
        }
      }
      return;
    }
    if (!other) return;
  }

  if (ruleForm.signTime && ruleForm.signTime.length > 0) {
    ruleForm.signStartTime = ruleForm.signTime[0]
      ? getDay(ruleForm.signTime[0])
      : '';
    ruleForm.signEndTime = ruleForm.signTime[1]
      ? getDay(ruleForm.signTime[1])
      : '';
  } else {
    ruleForm.signStartTime = '';
    ruleForm.signEndTime = '';
  }

  if (ruleForm.type == '4' || ruleForm.type == '2') {
    ruleForm.userDTO.mobile = ruleForm.mobile;
    ruleForm.userDTO.userName = ruleForm.userName;
    ruleForm.userDTO.accountNumber = ruleForm.accountNumber;
  }
  ruleForm.chargerDto.chargingThreshold = ruleForm.chargingThreshold;
  ruleForm.chargerDto.stationIds = ruleForm.stationIds;
  if (ruleForm.type == '1') {
    ruleForm.chargerDto.isLimit = ruleForm.isLimit;
  } else {
    ruleForm.chargerDto.isLimit = '';
  }
  if (ruleForm.isDeduction == '1' || !ruleForm.isDeduction) {
    ruleForm.superiorLimit = '';
  }
  ruleForm.chargerDto.limitType = ruleForm.limitType;
  ruleForm.chargerDto.orgIds = ruleForm.orgIds;
  if (ruleForm.limitType == '0' && orgTree.value) {
    ruleForm.chargerDto.orgIds = [];
    const treeOrg = orgTree.value?.getCheckedNodes();
    treeOrg.forEach((item: any) => {
      if (item.type !== 'CHANNEL') {
        ruleForm.chargerDto.orgIds.push(item.id);
      }
    });
  }
  if ((ruleForm.type == '0' && ruleForm.attr !== '3') || ruleForm.type == '1') {
    ruleForm.settlementTime = '';
  }

  if (ruleForm.type == '0') {
    ruleForm.businessLicense = ruleForm.businessLicense1;
  }

  if (ruleForm.type !== '0') {
    ruleForm.attr = '';
  }

  console.log('submit---', ruleForm);
  if (id) {
    updateCompany(ruleForm).then((res: any) => {
      emit('clear-cache');
      back();
    });
  } else {
    addCompany(ruleForm).then((res: any) => {
      emit('clear-cache');
      back();
    });
  }
};
</script>